<template>
  <div>
    <h3>{{dict_title[isPlayer]}}</h3>
    <el-row class="insertFrom" type="flex" justify="start">
      <el-col :span="5"></el-col>
      <el-col :span="10">
        <el-form inline-message ref="insertFrom" :model="insertFrom" :rules="rules" label-width="150px">
          <el-form-item label="身份证号" prop="idNo">
            <el-popover placement="top" title="提示" trigger="click" content="点击右侧扳手,生成一个临时身份证号码">
              <el-input slot="reference" v-model.trim="insertFrom.idNo">
                <div slot="prepend" style="font-size: 80%">{{insertFrom.idNo.length}} / 20</div>
                <el-button slot="append" icon="iconfont icon-banshou" @click.stop="birthdayFormVisible = true">
                </el-button>
              </el-input>
            </el-popover>
          </el-form-item>
          <el-form-item label="全名" prop="name">
            <el-input v-model="insertFrom.name"></el-input>
          </el-form-item>
          <el-form-item label="姓" prop="familyName">
            <el-input v-model="insertFrom.familyName"></el-input>
          </el-form-item>
          <el-form-item label="名" prop="givenName">
            <el-input v-model="insertFrom.givenName"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="insertFrom.genderId" filterable clearable style="width: 100%;" placeholder="请选择">
              <el-option label="男" :value="1"></el-option>
              <el-option label="女" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="生日">
            <el-date-picker v-model="insertFrom.birthday" type="date" style="width: 100%;" placeholder="例如: 2016-01-01">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="照片">
            <el-upload class="upload-demo" drag action="/person/personDetail" :show-file-list="false"
              :auto-upload="false" :on-change="beforeAvatarUpload">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-upload"></i>
              <div class="el-upload__text">将照片拖到此处<br>或<em>点击上传</em></div>
            </el-upload>
            <el-button type="success" size="mini" @click="clearAvatar">清除照片</el-button>
          </el-form-item>
          <el-form-item label="签发机关">
            <el-input v-model="insertFrom.issuing"></el-input>
          </el-form-item>
          <el-form-item label="户籍地址">
            <el-input v-model="insertFrom.address"></el-input>
          </el-form-item>
          <el-form-item label="民族">
            <el-input v-model="insertFrom.nation"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="perStatusId">
            <el-radio v-model="insertFrom.perStatusId" label="1">使用中</el-radio>
            <el-radio v-model="insertFrom.perStatusId" label="2">注销</el-radio>
          </el-form-item>
          <el-form-item>
            <el-button type="success" size="small" icon="el-icon-s-promotion" @click="addToPerson">下一步</el-button>
            <el-button type="success" size="small" icon="el-icon-s-tools" @click="readIDCard">机读</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="9"></el-col>
    </el-row>
    <el-dialog title="选择一个生日:" :visible.sync="birthdayFormVisible" width="420px">
      <el-form :model="birthdayForm" ref="birthdayForm">
        <el-form-item label="生日:" label-width="60px" prop="birthday"
          :rules="[{ required: true, message: '请选择一个生日', trigger: 'blur' },]">
          <el-date-picker v-model="birthdayForm.birthday" type="date" style="width: 100%;" placeholder="例如: 2016-01-01">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="性别:" label-width="60px" prop="genderId"
          :rules="[{ required: true, message: '请选择性别', trigger: 'blur' },]">
          <el-radio v-model="birthdayForm.genderId" label="1">男</el-radio>
          <el-radio v-model="birthdayForm.genderId" label="2">女</el-radio>
        </el-form-item>
        <el-form-item>
          <el-button type="success" style="float: right;" size="small" @click="autoGenerateID" icon="el-icon-check">好
          </el-button>
          <el-button type="warning" style="float: right;margin-right: 20px;" size="small"
            @click="birthdayFormVisible = false" icon="el-icon-refresh-left">放弃</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import {
    personDetail,
    personByIdNo
  } from '@/api/person.js'
  import {
    validIdNo
  } from '@/utils/validate.js'
  export default {
    props: ['empOrPlayer'],
    data() {
      const validDataIdNo = (rule, value, callback) => {
        if (!validIdNo(value)) {
          callback(new Error('请输入正确的身份证号'))
        } else {
          this.validPersonByIdNo()
          callback()
        }
      }
      return {
        dict_title: {
          1: '运动员建档',
          2: '教职员建档'
        },
        isPlayer: 1,
        insertFrom: {
          name: '',
          idNo: '',
          genderId: '',
          givenName: '',
          familyName: '',
          birthday: '',
          perStatusId: '',
          issuing: '',
          nation: '',
          address: '',
        },
        imageUrl: '',
        imageBase64: '',
        rules: {
          idNo: [{
            required: true,
            message: '请输入正确的身份证号',
            trigger: 'blur',
            validator: validDataIdNo
          }, ],
          name: [{
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }, ],
          perStatusId: [{
            required: true,
            message: '请选择状态',
            trigger: 'blur'
          }, ],
        },
        birthdayFormVisible: false,
        birthdayForm: {
          birthday: '',
          genderId: '',
        },
        newPerson: true,
        socket: null,
        sendFlag: 0,
        zpFormat: null,
      }
    },
    created() {
      if (this.empOrPlayer) {
        this.isPlayer = this.empOrPlayer
      } else {
        this.isPlayer = window.sessionStorage.getItem('isPlayer')
      }
      document.title = this.dict_title[this.isPlayer]
      this.openReader()
    },
    watch: {
      'insertFrom.idNo': {
        handler(newVal, oldVal) {
          this.insertFrom.idNo = newVal.toUpperCase()
        },
        deep: true
      }
    },
    methods: {
      readIDCard() {
        try {
          if (this.socket.readyState == 1) {
            this.socket.send("EST_Reader_ReadIDCard#");
          } else {
            this.$message.warning("未找到控件，请检查控件是否安装.");
          }
        } catch (ex) {
          this.$message.warning("连接异常,请检查是否成功安装控件.");
        }
      },
      // 机读
      openReader() {
        var host = "ws://127.0.0.1:33666"; //客户端电脑本地IP，非服务器IP，无需修改
        var _this = this
        if (_this.socket == null) {
          _this.socket = new WebSocket(host);
          // _this.$message.success("建立连接.");
        } else {
          _this.$message.success("已初始化.");
        }
        try {
          _this.socket.onopen = function() {
            // _this.$message.success("初始化成功."); //可以注释
            // getVersion(); //可以注释：控件版本号
          };
          _this.socket.onclose = function() {
            _this.$message.warning("读卡服务已经断开.");
          };
          _this.socket.onerror = function() {
            _this.$message.warning("请检查控件是否正常安装，下载地址：");
          };
          _this.socket.onmessage = function(msg) {
            if (typeof msg.data == "string") {
              var msgM = msg.data + "";
              var msgJson = JSON.parse(msgM);
              //_this.$message.success(msgM);
              switch (msgJson.fun) {

                case "EST_GetVersion#":
                  _this.$message.success("版本号：" + msgJson.errMsg);
                  break;

                case "EST_Reader_ReadIDCard#":
                  if (msgJson.rCode == "0") {
                    //获得身份信息
                    // document.execCommand('Refresh')
                    _this.insertFrom.name = msgJson.name; //姓名
                    var sex = msgJson.sex;
                    var gender = 1;
                    if (sex == '男') gender = 1
                    if (sex == '女') gender = 2
                    _this.insertFrom.genderId = gender; //性别
                    // $("#text_sex").trigger('change');
                    _this.insertFrom.nation = msgJson.nation; //民族
                    _this.insertFrom.birthday = _this.$moment(msgJson.birth + "").format(
                      "YYYY-MM-DD"); //出生日期
                    _this.insertFrom.address = msgJson.address; //地址
                    _this.insertFrom.idNo = msgJson.certNo; //身份证号
                    _this.insertFrom.issuing = msgJson.department; //签发机关
                    //                                document.getElementById("text_effDate").value = msgJson.match(/beginPeriodOfValidity(\S*)beginPeriodOfValidity/)[1];       //有效日期起始
                    //                                document.getElementById("text_expDate").value = msgJson.match(/endPeriodOfValidity(\S*)endPeriodOfValidity/)[1];        //有效日期截止
                    var src = "data:image/png;base64," + msgJson.base64Data; //显示图片
                    var name = _this.insertFrom.name.split('');
                    var givenName = ""
                    for (var i = 0; i < name.length; i++) {
                      if (i == 0)
                        _this.insertFrom.familyName = name[0];
                      else {
                        givenName += name[i]
                      }
                    }
                    _this.insertFrom.givenName = givenName;

                    _this.imageUrl = src
                    _this.imageBase64 = src
                    // $("#test").attr('src', src);
                    // $("#inputFileToLoad").trigger('change');
                    // $('#text_idNum').trigger('blur');
                    // $('#addToPlayer').removeClass('disabled');
                    // $('#addToEmployee').removeClass('disabled');
                    // _this.$message.success(msgJson.errMsg);
                  } else if (msgJson.rCode == "-2") {
                    _this.$message.warning("请放身份证");
                  } else {
                    _this.$message.warning(msgJson.errMsg);
                  }
                  break;


                default:
                  break;
              }
            } else {
              alert("连接异常,请检查是否成功安装控件.");
            }
          };
        } catch (ex) {
          alert("连接异常,请检查是否成功安装控件.");
        }
      },
      // 生成身份证
      autoGenerateID() {
        this.$refs.birthdayForm.validate((valid) => {
          if (valid) {
            let fakeBirth = this.$moment(this.birthdayForm.birthday).format('YYYY-MM-DD')
            let date = new Date();
            let hour = '' + date.getHours();
            if (hour.length == 1) hour = '0' + hour;
            // 正则表达式全局替换
            let fakeBirthStr = fakeBirth.replace(/-/g, '');
            let start = '9';
            let random5 = parseInt(Math.random() * 100000);
            let random1 = parseInt(Math.random() * 10);
            let gender = this.birthdayForm.genderId
            let fakeId = start + random5 + fakeBirthStr + hour + gender + random1;
            this.insertFrom.idNo = fakeId
            this.validPersonByIdNo()
            this.birthdayFormVisible = false
            this.$refs.insertFrom.clearValidate('idNo');
          } else {
            return false
          }
        })
      },
      // 获取生日性别
      getBirthdayAndGender() {
        var birthdayno, birthdaytemp
        if (this.insertFrom.idNo.length == 18) {
          birthdayno = this.insertFrom.idNo.substring(6, 14)
        } else if (this.insertFrom.idNo.length == 15) {
          birthdaytemp = this.insertFrom.idNo.substring(6, 12)
          birthdayno = "19" + birthdaytemp
        }
        this.insertFrom.birthday = birthdayno.substring(0, 4) + "-" + birthdayno.substring(4, 6) + "-" + birthdayno
          .substring(6, 8)
        var sexno, sex
        if (this.insertFrom.idNo.length == 18) {
          sexno = this.insertFrom.idNo.substring(16, 17)
        } else if (this.insertFrom.idNo.length == 15) {
          sexno = this.insertFrom.idNo.substring(14, 15)
        }
        var tempid = sexno % 2;
        if (tempid == 0) {
          sex = 2
        } else {
          sex = 1
        }
        this.insertFrom.genderId = sex
      },
      validPersonByIdNo() {
        personByIdNo({
          idNo: this.insertFrom.idNo
        }).then(res => {
          if (res.code === 200) {
            if (res.data) {
              this.insertFrom.name = res.data.name
              this.insertFrom.idNo = res.data.idNo
              this.insertFrom.genderId = res.data.genderId
              this.insertFrom.givenName = res.data.givenName
              this.insertFrom.familyName = res.data.familyName
              this.insertFrom.birthday = res.data.birthday
              this.insertFrom.perStatusId = res.data.perStatusId
              this.newPerson = false
            } else {
              this.getBirthdayAndGender()
              this.newPerson = true
            }
          }
        })
      },
      addToPerson() {
        let data = []
        if (this.insertFrom.name) data.name = this.insertFrom.name
        if (this.insertFrom.idNo) data.idNo = this.insertFrom.idNo
        if (this.insertFrom.genderId) data.genderId = this.insertFrom.genderId
        if (this.insertFrom.givenName) data.givenName = this.insertFrom.givenName
        if (this.insertFrom.familyName) data.familyName = this.insertFrom.familyName
        if (this.insertFrom.birthday) data.birthday = this.$moment(this.insertFrom.birthday).format('YYYY-MM-DD') +
          ' 00:00:00'
        if (this.insertFrom.perStatusId) data.perStatusId = this.insertFrom.perStatusId
        if (this.insertFrom.issuing) data.issuing = this.insertFrom.issuing
        if (this.insertFrom.nation) data.nation = this.insertFrom.nation
        if (this.insertFrom.address) data.address = this.insertFrom.address
        data.isPlayer = this.isPlayer
        if (this.imageUrl) {
          data.photo = this.imageBase64
        }
        this.$refs.insertFrom.validate((valid) => {
          if (valid) {
            personDetail(data).then(res => {
              if (res.code === 200) {
                window.sessionStorage.setItem('pId', res.data.pId)
                if (this.isPlayer == 1) {
                  this.$router.push({
                    path: '/playerDetail',
                    name: 'playerDetail',
                    params: {
                      newPerson: this.newPerson
                    }
                  })
                } else if (this.isPlayer == 2) {
                  this.$router.push({
                    path: '/empDetail',
                    name: 'empDetail',
                    params: {
                      newPerson: this.newPerson
                    }
                  })
                }
              } else {
                this.$message.error('提交错误')
              }
            })
          } else {
            return false;
          }
        })
      },
      clearAvatar() {
        this.imageUrl = ''
        this.imageBase64 = ''
      },
      getBase64(file) {
        return new Promise(function(resolve, reject) {
          let reader = new FileReader();
          let imgResult = "";
          reader.readAsDataURL(file);
          reader.onload = function() {
            imgResult = reader.result;
          };
          reader.onerror = function(error) {
            reject(error);
          };
          reader.onloadend = function() {
            resolve(imgResult);
          };
        });
      },
      beforeAvatarUpload(file) {
        const isJPG = file.raw.type === 'image/png' || file.raw.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.$message.error('上传头像只能是jpg/png格式!');
        } else if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        } else {
          this.imageUrl = URL.createObjectURL(file.raw);
          this.getBase64(file.raw).then(res => {
            this.imageBase64 = res
          })
        }
      }
    },
  }
</script>

<style lang="scss" scoped>
  .insertFrom {
    width: 100%;
    height: 100%;
    padding: 10px 10px 50px 10px;
    background-color: #FFFFFF;

    .upload-demo {
      width: 150px;
      height: 210px;
    }
  }
</style>
